"""
    Written By: Glenn Dayton  7/2011 - 8/2011
    views.py passes database and user information to the .html django templates
    randimization for models is contained in the views.py, as well as all of the template handlings
"""
#from safc.models import WebGLModel
from safc.forms import SignIn, InteractionForm, CreateAccount
from django.http import Http404
from django.template import Context, loader
from django.shortcuts import render_to_response, get_object_or_404
from django.http import *
from django.contrib.auth.models import User
from safc.models import WebGLModel, Interaction, OrigWebGLModel
from django.contrib.auth import authenticate, login, logout
import array, math, datetime, random
import re

def index(request):
    null = 'null'
    t = loader.get_template('index.html')
    c = Context({
        'null': null,
    })
    return HttpResponse(t.render(c))
    
def denied(request):
    null = 'null'
    t = loader.get_template('denied.html')
    c = Context({
        'null': null,
    })
    return HttpResponse(t.render(c))

def incorrect(request):
    null = 'null'
    t = loader.get_template('incorrect.html')
    c = Context({
        'null': null,
    })
    return HttpResponse(t.render(c))
    
def written(request):
    null = 'null'
    t = loader.get_template('written.html')
    c = Context({
        'null': null
    })
    return HttpResponse(t.render(c))
    
def bibliography(request):
    null = 'null'
    t = loader.get_template('bibliography.html')
    c = Context({
        'null': null,
    })
    return HttpResponse(t.render(c))
    
def conformation(request):
    null = 'null'
    t = loader.get_template('conformation.html')
    c = Context({
        'null': null,
    })
    return HttpResponse(t.render(c))
    
def tutorial(request):
    null = 'null'
    t = loader.get_template('tutorial.html')
    c = Context({
        'null': null,
    })
    return HttpResponse(t.render(c))
    
def begin(request):
    if request.user.is_authenticated():
        """
         written by: Glenn Dayton
         date: 8/2/11
         Retrieve models from verified area, and display them based on the m/f and age metrics
         open up the restricted text file
         parse the model numbers
         """
        """ #STARTS HERE#"""
        numberOfOrigModels = OrigWebGLModel.objects.count()
        
        txtFile = file('/var/www/data/'+ request.user.username +'.txt', 'rb')
        
        line = txtFile.readline().rstrip().split(',')
        txtFile.close()
        line.sort()
        txtElements = len(line)-1
        display_Mods = [0]*3
        original_id = mod0 = mod1 = mod2 = mod0_id = mod1_id = mod2_id = randomNum = randomNum2 = randomNum3 = 0
        
        #deal with too little models
        if txtElements > 3:
            fls2 = True
            while fls2:
                randomNum = random.randint(1,txtElements)
                randomNum2 = random.randint(1,(txtElements-1))
                if randomNum != randomNum2:
                    randomNum3 = random.randint(1,(txtElements-2))
                    if randomNum != randomNum2 and (randomNum3 != randomNum2 and randomNum3 != randomNum):
                        fls2 = False
                    else:
                        fls2 = True
                else:
                    fls2 = True
            
            #first model
            original_id = line[randomNum]
                #--------assign a random spot to the model
            randomSpot = random.randint(0,2)
                #--------switch statment?
            if randomSpot == 0:
                mod0_id = line[randomNum]
                line.pop(randomNum)
                display_Mods[0]=1
            elif randomSpot == 1:
                mod1_id = line[randomNum]
                line.pop(randomNum)
                display_Mods[1]=1
            else:
                mod2_id = line[randomNum]
                line.pop(randomNum)
                display_Mods[2]=1
            
            #second model                                        
            if display_Mods[0] == 1:
                mod1_id = line[randomNum2]
                display_Mods[1]=1
                line.pop(randomNum2)
            elif display_Mods[1] == 1:
                mod2_id = line[randomNum2]
                display_Mods[2]=1
                line.pop(randomNum2)
            else:
                mod0_id = line[randomNum2]
                display_Mods[0]=1
                line.pop(randomNum2)
             
            # third model                   
            one = display_Mods[0]
            two = display_Mods[1]
            thr = display_Mods[2]
            if one == 1 and two == 1:
                mod2_id = line[randomNum3]
                line.pop(randomNum3)
            elif one == 1 and thr == 1:
                mod1_id = line[randomNum3]
                line.pop(randomNum3)
            else:
                mod0_id = line[randomNum3]
                line.pop(randomNum3)
        else:
            #make a default model choce that shows the survey is over.
            original_id = 1
            mod0_id = 1
            mod1_id = 1
            mod2_id = 1
                        
        #---stops here---
        """
        original_id = 4
        mod0_id = 7
        mod1_id = 6
        mod2_id = 4
        """
        #original = original_id #<= select from the original database
        original = OrigWebGLModel.objects.get(pk=original_id)
        #mod0 = mod0_id
        mod0 = WebGLModel.objects.get(pk=mod0_id)
        #mod1 = mod1_id  # randomly assign one of the models the original image
        mod1 = WebGLModel.objects.get(pk=mod1_id)
        #mod2 = mod2_id
        mod2 = WebGLModel.objects.get(pk=mod2_id)
        correct = original_id
        if request.method == 'POST':
            form = InteractionForm(request.POST)
            if form.is_valid():
                user_id_refy = request.user.id
                webgl_id_refsy = form.data['webgl_id_refs']
                # num_images <= hidden data field determined w/ javascript
                selections_gety = form.cleaned_data['checkboxes']
                correcty = form.data['correct']
                date_timey = datetime.datetime.now()
                milliy = float(form.data['milli'])
                case_infoy = form.cleaned_data['textbox']
                choicesy = form.data['s']
                
                # no switch stmt, what ?!!
                selectionsy = [0]*6
                for i in selections_gety:
                    if i == "nose":
                        selectionsy[0] = 1
                    elif i == "ears":
                        selectionsy[1] = 1
                    elif i == "hair":
                        selectionsy[2] = 1
                    elif i == "markings":
                        selectionsy[3] = 1
                    elif i == "wrinkles":
                        selectionsy[4] = 1
                    elif i == "eyebrows":
                        selectionsy[5] = 1
                        
                selections_string = ""
                for ing in range(0,5):
                    selections_string += str(selectionsy[ing])+","
                selections_string += str(selectionsy[5])
                        
                
                if choicesy == correcty:
                    num_imagesy = 0
                else:
                    num_imagesy = 1
                
                file_line = ""
                line.sort()
                for a in line:
                    file_line += str(a + ',')
                    
                open = Interaction(user_id_ref=user_id_refy, webgl_id_refs=webgl_id_refsy, num_images=num_imagesy, case_info=case_infoy, selections=selections_string, datetime=date_timey, milli=int(milliy)) #remove the integer conversion
                open.save()
                userFile = file('/var/www/data/'+ request.user.username +'.txt', 'w')
                userFile.write(file_line)
                
                return HttpResponseRedirect('/safc/begin')
                #make an if statement here, debugging purposes --->
                #return HttpResponse("<b>Correct Id:</b><br />" + correcty + "<br /><b>Datetime:</b><br />" + date_timey + "<br /><b>Seconds</b><br />" + milliy + "<br /><b>Information:</b><br />" + case_infoy + "<br /><b>WebGL ID Refs</b><br />" + webgl_id_refsy + "<br /><b>Choices:</b><br />" + choicesy + "<br /><b>User ID:</b><br />" + str(user_id_refy) + "<br /><b>Num Images:</b><br />" + str(num_imagesy) + "<br /><b>Selections</b><br />" +str(selectionsy))
        else:
            form = InteractionForm()
            
        return render_to_response("begin.html", {
            'form': form,
            'original': original,
            'mod0': mod0,
            'mod1': mod1,
            'mod2': mod2,
            'correct': correct,
        })
    else:
        return HttpResponseRedirect('/safc/signin')
    
def createaccount(request):
    users_taken = User.objects.all()
    if request.method == 'POST':
        form = CreateAccount(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            password_one = form.cleaned_data['password_one']
            password_two = form.cleaned_data['password_two']
            
            c = User.objects.create_user(name, email, password_one)
            file_line = ""
            for k in OrigWebGLModel.objects.all():
                file_line += str(k.id)+','
            file_line = file_line[:-1]
                
            if len(password_one) == len(password_two):
                if password_one == password_two:
                    filename = "/var/www/data/"+name+".txt"
                    f = open(filename, 'w')
                    f.write(file_line)
                    f.close()
                    c.save()
                    f = loader.get_template('conformation.html')
                    c = Context({
                        'name': name,
                        'email': email,
                    })
                    return HttpResponse(f.render(c))
    else:
        form = CreateAccount()
        users_taken = User.objects.all()
        
    return render_to_response('createaccount.html', {
        'form': form,
        'users_taken': users_taken,
    })
    
def signin(request):
    if request.method == 'POST':
        form = SignIn(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    #valid account
                    login(request, user)
                    return HttpResponseRedirect('../../safc')
                else:
                    #disabled account
                    null = 'null'
                    t = loader.get_template('denied.html')
                    c = Context({
                        'null': null,
                    })
                    return HttpResponse(t.render(c))
            else:
                #invalid login
                null = 'null'
                t = loader.get_template('incorrect.html')
                c = Context({
                    'null': null,
                })
                return HttpResponse(t.render(c))
            
            #return HttpResponse('You have been signed in')
            
    else:
        form = SignIn()
        
    return render_to_response('signin.html', {
        'form': form,
    })
    
def logoutuser(request):
    logout(request)
    return HttpResponseRedirect('../../safc')
    
def user(request):
    if request.user.is_authenticated():
        username = "Welcome, " + request.user.username
    else:
        return HttpResponseRedirect('../logerror')
    t = loader.get_template('user.html')
    c = Context({
        'username': username,
    })
    return HttpResponse(t.render(c))
    
def logerror(request):
    null = 'null'
    t = loader.get_template('logerror.html')
    c = Context({
        'null': null,
    })
    return HttpResponse(t.render(c))

def analytics(request):
    # Glenn Dayton 8/4/11
    spots = [0]*30
    selections = [0]*6
    interactions = Interaction.objects.all()
    num_models = Interaction.objects.count()
    yes_mods = Interaction.objects.filter(num_images=1).count()
    no_mods = Interaction.objects.filter(num_images=0).count()
    
    # looking a bit like unmaintainable code
    secs_list = ""
    seclections_fin = ""
    f = 0
    total = 0
    for i in Interaction.objects.all():
        k = int(i.milli)
        if k <= 30:
            spots[k-1] +=1
        total += i.milli
    #VVV for the google charts image VVV
    for i in range(0,29):
        secs_list += str(spots[i])+","
    secs_list += str(spots[29])
    
    #secondary selections list for the analytics
    for ml in Interaction.objects.all():
        mini_sel = ml.selections.rstrip().split(',')
        g = 0
        for pgb in mini_sel:
            if mini_sel[g] == "1":
                selections[g] += 1
            g += 1
            
     
    t = loader.get_template('analytics.html')
    c = Context({
        'interactions': interactions,
        'num_models': num_models,
        'yes_mods': yes_mods,
        'no_mods': no_mods,
        'secs_list': secs_list,
        'selections': selections,
        'spots': spots,
    })
    return HttpResponse(t.render(c))
    
def deepanalytics(request, interaction_id):
    interaction = Interaction.objects.get(pk=interaction_id)
    t = loader.get_template('deepanalytics.html')
    c = Context({
        'interaction': interaction,
    })
    return HttpResponse(t.render(c))